package es;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/7/30 0:02
 * @since JDK 1.8
 *
 * Es工具类
 */
public class EsUtils {


    private static TransportClient client;

    private static final String TYPE="tweet";

    static {
        Settings settings = Settings.builder().put("cluster.name", "docker-cluster").build();
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddresses(new TransportAddress(InetAddress.getByName("192.168.217.128"), 9300));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加索引
     * @param indexName
     */
    public static void addIndex(String indexName, XContentBuilder source){
        IndexResponse response = client.prepareIndex(indexName, TYPE).setSource(source).get();
        System.out.println(JSONObject.toJSON(response));
    }

    //删除索引
    public static void delIndex(String indexName) {
        //DeleteResponse deleteResponse = client.prepareDelete(indexName, TYPE).get();
       // System.out.println(JSON.toJSONString(deleteResponse));
    }

    /**
     * 将对象返回成 XContentBuilder
     * @param objectMap
     * @return
     * @throws Exception
     */
    public static XContentBuilder addXContentBuilder(Map<String,Object> objectMap) throws Exception{
        XContentBuilder xContentBuilder=XContentFactory.jsonBuilder().startObject();
        for (Map.Entry<String, Object> o: objectMap.entrySet()) {
            xContentBuilder.field(o.getKey(),o.getValue());
        }
        return xContentBuilder.endObject();
    }

    /**
     * 添加数据通过索引
     * @param objectMap
     * @param indexName
     * @throws Exception
     */
   public static void addOneDataByIndexName(Map<String, Object> objectMap,String indexName) throws Exception{
        XContentBuilder source=addXContentBuilder(objectMap);
        IndexResponse response =client.prepareIndex(indexName, TYPE).setSource(source).execute().actionGet();
        System.out.println("response.version():"+response.getVersion());
    }


    /**
     * 通过索引去搜索数据
     * @param keyword
     * @param field
     * @param indexName
     * @param page
     * @param size
     * @return
     */
    public static Map<String, Object> keywordSearchByIndex(String keyword,String field,String indexName,Integer page,Integer size) {
        SearchRequestBuilder searchBuilder = client.prepareSearch(indexName).setTypes(TYPE);
        WildcardQueryBuilder queryBuilder1 = QueryBuilders.wildcardQuery(field, "*"+keyword+"*");
        Integer pageNum=(page-1)*size;
        SearchResponse reponse = searchBuilder.setQuery(queryBuilder1).setFrom(pageNum).setSize(size).setExplain(true).execute().actionGet();
        SearchHits searchHits =reponse.getHits();
        Long count = searchHits.getTotalHits();
        System.out.println("总数：" + count);
        SearchHit[] searchHitArr = searchHits.getHits();
        List<Map<String, Object>> objectList=new ArrayList<>();
        for(SearchHit searchHit : searchHitArr){
            objectList.add(searchHit.getSourceAsMap());
        }
        Map<String, Object> map=new HashMap<>();
        map.put("data",objectList);
        map.put("total",count);
        map.put("current",page);
        map.put("size",size);
        return map;
    }





}
